package cn.itcast.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.dao.Sys_menuDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Menu;
import cn.itcast.service.Sys_menuService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Service(version = "1.0.0")
@Slf4j
public class Sys_menuServiceImpl implements Sys_menuService {

    @Autowired
    private Sys_menuDao sysMenuDao;

    @Override
    public PageResult queryMenuList(Integer page, Integer pageSize, String queryString) {
        PageHelper.startPage(page,pageSize);
        Page<Menu> menus = this.sysMenuDao.selectByCondition(queryString);

        menus.stream().filter(menus1->menus1.getLevel()==1)
                .sorted(Comparator.comparing(Menu::getPriority))
                .forEach(menus1->{ menus1.setChildren(this.sysMenuDao.findByIds(menus1.getId())); });
        return new PageResult(menus.getTotal(),menus);
    }

    @Override
    public List<Menu> queryMenuList(Integer page, Integer pageSize) {

        return this.sysMenuDao.findAll();
    }

    @Override
    public Boolean saveMenus(Map<String, String> map,String permissionIds) {
        try {
            String name = map.get("name");
            String linkUrl = map.get("linkUrl");
            String priority = map.get("priority");
            String description = map.get("description");
            String icon = map.get("icon");
            String parentMenuId = map.get("parentMenuId");
            String level = map.get("level");
            List<String> ids=null;
            if (StrUtil.isNotEmpty(permissionIds)) {
                if (StrUtil.contains(permissionIds, ',')) {
                    ids = StrUtil.split(permissionIds, ',');
                }else {
                    ids.add(permissionIds);
                }
            }
            Menu menu = new Menu();
            menu.setName(name);
            menu.setLinkUrl(linkUrl);
            menu.setPriority(Convert.toInt(priority));
            menu.setDescription(description);
            menu.setIcon(icon);
            menu.setParentMenuId(Convert.toInt(parentMenuId));
            menu.setLevel(Convert.toInt(level));
            this.sysMenuDao.add(menu);
            return this.savePermission(menu.getId(),ids);
        } catch (Exception e) {
            log.error("添加菜单错误，id="+permissionIds,e);
        }
        return false;
    }

    @Override
    public Menu queryEditMenus(Integer id) {
        return this.sysMenuDao.findById(id);
    }

    @Override
    public Boolean editMenus(Menu menus,String permissionIds) {
        try {
            if (ObjectUtil.isEmpty(menus)){
                return false;
            }
            List<String> ids=null;
            if (StrUtil.isNotEmpty(permissionIds)) {
                if (StrUtil.contains(permissionIds, ',')) {
                    ids = StrUtil.split(permissionIds, ',');
                }else {
                    ids.add(permissionIds);
                }
            }
            this.sysMenuDao.update(menus);
            Boolean aBoolean = this.sysMenuDao.delPermission(menus.getId());
            if (aBoolean){
                this.savePermission(menus.getId(),ids);
            }
            return true;
        } catch (Exception e) {
            log.error("编辑出错，menu="+menus+",permissionIds="+permissionIds,e);
        }
        return false;
    }

    /**
     *保存t_menu_permission表内容
     * @param menuID，permissionIds
     * @return
     */
    private Boolean savePermission(Integer menuID,List<String> permissionIds){
        try {
            if (CollUtil.isNotEmpty(permissionIds)){
                if (permissionIds.size()==1){
                    this.sysMenuDao.saveMenuToPermission(menuID,Convert.toInt(permissionIds.get(0)));
                }else {
                    for (String id : permissionIds) {
                        this.sysMenuDao.saveMenuToPermission(menuID,Convert.toInt(id));
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean delMenus(Integer id) {
        List<Menu> byIds = this.sysMenuDao.findByIds(id);
        if (CollUtil.size(byIds)>0){
            return false;
        }
        if (this.sysMenuDao.findPermissionId(id).size()>0){
            return false;
        }
        return this.sysMenuDao.deleteById(id);
    }

    @Override
    public List<Integer> queryMenusOfPermissions(Integer id) {
        return   this.sysMenuDao.findPermissionId(id);
    }
}
